document.addEventListener("DOMContentLoaded", loginAuth, false);
let crossOrigin = "/api";
let dict = {};

function ajax(url, type, data, func, isNormalData) {
    let isTruth = (isEmpty(isNormalData) || isNormalData);
    let isType = (type === "PUT" || type === "POST");
    layui.use('jquery', () => {
        let $ = layui.jquery;
        $.ajax({
            url: crossOrigin + url,
            type: type,
            data: isTruth ? (isType ? JSON.stringify(data) : data) : data,
            processData: isTruth ? isNormalData : false,
            contentType: isTruth ? (isType ? "application/json" : "application/x-www-form-urlencoded;charset=UTF-8") : false,
            xhrFields: {
                withCredentials: true
            },
            success: func
        });
    });
}

/* 判断元素是否为空 */
function isEmpty(element) {
    return element === undefined || element == null || element === '';
}

/* 填充字典 */
function fillDict() {
    if (!isEmpty(sessionStorage.getItem("dict"))) return;
    ajax("/admin/dict/list", "GET", "", (res) => {
        let data = res.data;
        let container = {};
        for (let i = 0; i < data.length; i++) {
            let type = data[i].type, code = data[i].code, text = data[i].text;
            if (isEmpty(container[type])) {
                container[type] = [];
            }
            let map = {};
            map[code] = text;
            container[type].push(map);
        }
        let dict = {};
        for (let key in container) {
            let attr = {};
            for (let obj of container[key]) {
                let attrKey = Object.keys(obj);
                attr[attrKey] = obj[attrKey];
            }
            dict[key] = attr;
        }
        sessionStorage.setItem("dict", JSON.stringify(dict));
    });
}

/* 获取字典数据 */
function getDict() {
    return JSON.parse(sessionStorage.getItem("dict"));
}

/* 图片文件上传 */
function upload(elem, url) {
    layui.use('upload', function () {
        let $ = layui.jquery
            , upload = layui.upload;
        //普通图片上传
        let uploadInst = upload.render({
            elem: elem
            , url: crossOrigin.concat(url) //改成您自己的上传接口
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#showImg').attr('src', result); //图片链接（base64）
                });
            }
            , done: function (res) {
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败');
                }
                //上传成功
                sessionStorage.setItem("succeedUploadPath", JSON.stringify(res.data));
            }
            , error: function () {
                //失败状态，并实现重传
                let backText = $('#backText');
                backText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs img-reload">重试</a>');
                backText.find('.img-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });
    });
}

/* 过滤为空的表单属性 */
function filterFormOnNull(data) {
    for (let key in data) {
        if (data.hasOwnProperty(key) && isEmpty(data[key])) {
            delete data[key];
        }
    }
    return data;
}

/* 表单重渲染 */
function formRender() {
    layui.use('form', () => {
        let form = layui.form;
        form.render();
    });
}

function loginAuth() {
    let excludePath = ["login", "register"];
    for (let path of excludePath) {
        if (window.location.pathname.lastIndexOf(path) !== -1) return;
    }
    layui.use('jquery', () => {
        let $ = layui.jquery;
        $.ajax({
            url: "/api/back/admin/getAdmin", type: "GET",
            xhrFields: {withCredentials: true},
            success: (res) => {
                if (res.code !== 0) {
                    return window.location.replace("/login");
                }
            }
        });
    });
}

function getAdmin(callback) {
    layui.use('jquery', () => {
        let $ = layui.jquery;
        $.ajax({
            url: "/api/back/admin/getAdmin", type: "GET",
            xhrFields: {withCredentials: true},
            success: (res) => {
                if (res.code === 0) {
                    callback(res.data);
                }
            }
        });
    });
}

/* 日期格式化 */
function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "y+": date.getFullYear().toString(),        // 年
        "M+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "m+": date.getMinutes().toString(),         // 分
        "s+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        }
    }
    return fmt;
}

/* 解析url参数为对象 */
function parseSearchParams() {
    let search = window.location.search.replace("?", "");
    let searchArray = search.split("&");
    let obj = {};
    searchArray.forEach((val, idx) => {
        let key = val.split("=")[0];
        obj[key] = val.split("=")[1];
    });
    return obj;
}